package com.gift.common;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

//上传和下载
public class Plupload {
    /**
     *
     * @param request
     * @param folderName  为路径中间那一段和时间等一起组成mypath
     *              然后用request.getServletContext().getRealPath(myPath);生成全路径
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    public  Map plupload(HttpServletRequest request, String folderName)throws IllegalStateException, IOException {

        //初始化通用multipart解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //判断请求中是否有文件上传
        if (!multipartResolver.isMultipart(request)) {
            //请求为空，直接返回
            return null;
        }
        //解析请求，将文件信息放到迭代器里
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        Iterator<String> iterator = multiRequest.getFileNames();
        //取得上传文件
        MultipartFile file = multiRequest.getFile(iterator.next());
        if (null != file) {
            //取得当前上传文件的文件名称
            String myFileName = file.getOriginalFilename();
            //判断文件是否存在，文件名为空，则说明文件不
            if (myFileName.trim().length() > 0) {
                //获取文件格式
                //String type = file.getContentType();
                //String fileType = type.substring(type.indexOf("/") + 1);
                String fileType = myFileName.substring(myFileName.lastIndexOf("."));
                //重命名上传后的文件名
                String fileName = UUID.randomUUID().toString().substring(0, 12) + fileType;
                //定义上传路径
                String dateName = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")).toString();
                String myPath = "/WEB-INF/uploadFile/" + folderName + "/" + dateName + "/";     //为存储路径的后半段.
                String savePath = request.getServletContext().getRealPath(myPath);
                File tmpFile = new File(savePath);
                if (!tmpFile.exists()) {
                    //创建目录
                    tmpFile.mkdirs();
                }
                String path = savePath + fileName;
                //得到上传文件的保存目录，将上传的文件存放于WEB-INF目录下，不允许外界直接访问，保证上传文件的安全
                File localFile = new File(path);
                file.transferTo(localFile);
                JsonObj jsonObj = new JsonObj();
                jsonObj.setPath(myPath + fileName);
                Map map = new HashMap();
                map.put("jsonObj", jsonObj);
                map.put("filePath", myPath + fileName);
                map.put("myFileName", myFileName.substring(0, myFileName.lastIndexOf(".")));
                map.put("size", (int) file.getSize() / 1024);   //非精确文件大小
                map.put("fileType", fileType);
                return map;
            }
        }
        return null;
    }

    /**
     * 下载
     * @param request
     * @param annexUrl 相对路径
     * @param annexName 下载显示的名字
     * @return
     * @throws Exception
     */
    public ResponseEntity<byte[]> download(HttpServletRequest request,
                                           String annexUrl, String annexName) throws Exception {
        //下载文件路径
        String path = request.getServletContext().getRealPath(annexUrl);
        File file = new File(path);
        HttpHeaders headers = new HttpHeaders();
        //下载显示的文件名，解决中文名称乱码问题
        String downloadFielName = new String(annexName.getBytes("UTF-8"), "iso-8859-1");
        //通知浏览器以attachment（下载方式）打开图片
        headers.setContentDispositionFormData("attachment", downloadFielName);
        //application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);
    }
}
